﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;

namespace ExportManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SalesManagerEntities _sme = new SalesManagerEntities();
        private CollectionViewSource _exportManagerViewSource;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _exportManagerViewSource = ((CollectionViewSource)FindResource("ExportManager"));

            var x = (from c in _sme.tblOwners orderby c.ShortName select new { c.OwnerID, c.ShortName }).ToList();
            x.Insert(0, new { OwnerID = -1, ShortName = "All" });
            CollectionViewSource ownerFilterViewSource = ((CollectionViewSource)FindResource("OwnerFilter"));
            ownerFilterViewSource.Source = x;
            cmbOwnerFilter.SelectedValue = -1;
            cmbOwnerFilter.SelectionChanged += new SelectionChangedEventHandler(cmbOwnerFilter_SelectionChanged);
            cmbOwnerFilter_SelectionChanged(null, null);

            SqlConnection conn = (SqlConnection)((System.Data.EntityClient.EntityConnection)_sme.Connection).StoreConnection;
            if (conn.State != System.Data.ConnectionState.Open)
                conn.Open();
            SqlCommand cmm = conn.CreateCommand();
            cmm.CommandText = "select distinct name from msdb..sysschedules";
            SqlDataReader rdr = cmm.ExecuteReader();
            List<string> schedules = new List<string>();
            while (rdr.Read())
                schedules.Add(rdr.GetString(0));
            rdr.Close();
            ((CollectionViewSource)FindResource("Schedules")).Source = schedules;

            ((CollectionViewSource)FindResource("Owner")).Source = from c in _sme.tblOwners select c;
        }

        void cmbOwnerFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((Int32)cmbOwnerFilter.SelectedValue == -1)
                _exportManagerViewSource.Source = from c in _sme.tblExportManager where c.Active select c;
            else
                _exportManagerViewSource.Source = from c in _sme.tblExportManager where c.Active && c.OwnerID == (Int32)cmbOwnerFilter.SelectedValue select c;
            _exportManagerViewSource.View.CurrentChanged += new EventHandler(View_CurrentChanged);
            View_CurrentChanged(null, null);
        }

        void View_CurrentChanged(object sender, EventArgs e)
        {
            SetValue(EnableEditingProperty, (_exportManagerViewSource.View.CurrentItem != null));
        }

        public static readonly DependencyProperty EnableEditingProperty =
            DependencyProperty.Register("EnableEditing", typeof(bool), typeof(MainWindow));
        public bool EnableEditing
        {
            get { return (bool)GetValue(EnableEditingProperty); }
        }

        private void btnRunExport_Click(object sender, RoutedEventArgs e)
        {
            if (gridExports.SelectedItems.Count == 0)
            {
                MessageBox.Show("Please select at least one export to run");
                return;
            }
            List<Int32> exportIDs = new List<Int32>();
            foreach (tblExportManager em in gridExports.SelectedItems)
            {
                exportIDs.Add(em.ExportID);
            }

            RunExports dlg = new RunExports(exportIDs);
            dlg.ShowDialog();
        }

        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            tblExportManager oldExport = (tblExportManager)_exportManagerViewSource.View.CurrentItem;

            if (oldExport == null)
            {
                MessageBox.Show("Please select a valid export");
                return;
            }

            tblExportManager newExport = (tblExportManager)((IEditableCollectionView)_exportManagerViewSource.View).AddNew();
            newExport.Active = true;
            newExport.Name = oldExport.Name;
            newExport.ScheduleName = oldExport.ScheduleName;
            newExport.OwnerID = oldExport.OwnerID;
            newExport.FileName = oldExport.FileName;
            newExport.Query = oldExport.Query;
            newExport.Format = oldExport.Format;
            newExport.MailTo = oldExport.MailTo;
            newExport.MailCc = oldExport.MailCc;
            newExport.MailSubject = oldExport.MailSubject;
            newExport.MailBody = oldExport.MailBody;
            newExport.SendIfEmpty= oldExport.SendIfEmpty;
            newExport.AttachFile = oldExport.AttachFile;
            newExport.AttachFileIfEmpty = oldExport.AttachFileIfEmpty;
            newExport.OverwriteFile = oldExport.OverwriteFile;
            newExport.FtpDirectory = oldExport.FtpDirectory;
            newExport.FtpSite = oldExport.FtpSite;
            newExport.FtpUser = oldExport.FtpUser;
            newExport.FtpPwd = oldExport.FtpPwd;

            _sme.AddTotblExportManager(newExport);
            _exportManagerViewSource.View.MoveCurrentTo(newExport);
            txtName.Focus();
        }

        private void btnHistory_Click(object sender, RoutedEventArgs e)
        {
            tblExportManager export = (tblExportManager)_exportManagerViewSource.View.CurrentItem;

            if (export == null)
            {
                MessageBox.Show("Please select a valid export");
                return;
            }
            dlgExportHistory dlg = new dlgExportHistory(export);
            dlg.ShowDialog();
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            tblExportManager newExport = (tblExportManager)((IEditableCollectionView)_exportManagerViewSource.View).AddNew();
            newExport.Name = "New Export";
            newExport.Active = true;
            _sme.AddTotblExportManager(newExport);
            _exportManagerViewSource.View.MoveCurrentTo(newExport);
            txtName.Focus();
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            tblExportManager em = (tblExportManager)_exportManagerViewSource.View.CurrentItem;
            if (em == null)
            {
                MessageBox.Show("Please select a valid export");
                return;
            }

            if (MessageBox.Show("Are you sure you want to delete the export " + em.Name + " for " + em.Owner.ShortName, "Confirm Delete", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
            {
                em.Active = false;
                ((IEditableCollectionView)_exportManagerViewSource.View).Remove(em);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            _sme.SaveChanges();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (_sme.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified).Count() > 0)
            {
                MessageBoxResult result = MessageBox.Show("Do you want to save changes before closing?", "Save changes?", MessageBoxButton.YesNoCancel);
                if (result == MessageBoxResult.Cancel)
                    e.Cancel = true;
                if (result == MessageBoxResult.Yes)
                    _sme.SaveChanges();
            }
        }
    }
}
